package com.test.netty.handler;

import com.test.netty.entity.Invocation;
import com.test.netty.entity.URL;
import com.test.netty.factory.ProtocolFactory;
import com.test.netty.protocol.Protocol;
import com.test.netty.register.LoadBalance;
import com.test.netty.register.RemoteMapRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

public class MyInvocationHandler implements InvocationHandler {
    private final Class<?> interfaceClass;

    private Class<?> implClass;

    public MyInvocationHandler(Class<?> interfaceClass,Class<?> implClass) {
        this.interfaceClass = interfaceClass;
        this.implClass = implClass;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);
        List<URL> urlList = RemoteMapRegister.get(interfaceClass.getName());

        URL url = LoadBalance.random(urlList);
        Protocol protocol = ProtocolFactory.getProtocol();
        // 发送消息
        String result = protocol.send(url, invocation);
        System.out.println("MyInvocationHandler.invoke:" + result);

        return method.invoke(implClass.newInstance(), args);
    }
}
